/**
 * 用户管理
 */
const router = require('koa-router')();
const User = require('../models/userSchema');
const Counter = require('../models/counterSchema');
const Menu = require('../models/menuSchema');
const Role = require('../models/roleSchema');
const util = require('../utils/util');
const jwt = require('jsonwebtoken');
const log4js = require('../utils/log4j');
const md5 = require('md5');

router.prefix('/users')

router.post('/login', async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    console.log(userName, userPwd, md5(userPwd))
    const res = await User.findOne(
      { userName, userPwd: md5(userPwd) },
      'userId userName userEmail state role deptId roleList'
    )
    console.log('res: ', res);
    if (res) {
      const token = jwt.sign({
        data: res._doc,
      }, util.jwtKey, {
        expiresIn: '2 days'
      })
      log4js.info(`token: ${token}`);
      ctx.body = util.success({
        ...res._doc,
        token
      })
    } else {
      ctx.body = util.fail('账号或密码不正确')
    }
  } catch (error) {
    ctx.body = util.fail('服务端连接失败')
  }
})

router.post('/delete', async (ctx) => {
  const { userIds } = ctx.request.body
  try {
    let res = await User.updateMany({ _id: { $in: userIds } }, { state: 2 })
    if (res.acknowledged) {
      ctx.body = util.success(res, `共删除 ${res.modifiedCount} 条数据`)
      return
    }
    ctx.body = util.fail(`user 删除异常 ${res}`)
  } catch (error) {
    ctx.body = util.fail(`user 删除异常 ${error.stack}`)
  }
})

router.get('/list', async ctx => {
  const { userId, userName, state } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)

  const params = {}
  if (userId) params.userId = userId
  if (userName) params.userName = userName
  if (state && state != 0) params.state = state
  try {

    const query = User.find(params, { userPwd: 0 })
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await User.countDocuments(params);

    ctx.body = util.success({
      list,
      page: {
        ...page,
        total
      }
    })

  } catch (error) {
    console.error(error)
    ctx.body = util.fail(`查询异常: ${error.stack}`)
  }
})

router.post('/operate', async ctx => {
  try {
    console.log('operate - ctx.request.body', ctx.request.body)
    const { _id, userId, userName, userPwd, userEmail, mobile, sex, deptId,
      job, state, role, roleList, action } = ctx.request.body
    if (action === 'add') {
      if (!userName || !deptId) {
        ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR);
        return;
      }
      try {
        let oldUserRes = await User.findOne({ $or: [{ userName }] }, '_id userName userEmail');
        console.log('oldUserRes: ', oldUserRes);
        if (oldUserRes) {
          ctx.body = util.fail(`已存在重复信息, 请重新输入`)
          return
        }
        // id 自增
        let idResDoc = await Counter.findOneAndUpdate(
          { _id: 'userId' },
          { $inc: { sequence_value: 1 } },
          { new: true }
        );
        if (!idResDoc) {
          idResDoc = await Counter.create({
            _id: 'userId',
            sequence_value: 1000
          })
        }
        console.log('create user', idResDoc);
        await User.create({
          userId: idResDoc.sequence_value,
          userName,
          userEmail,
          role: 1, // 1 普通用户, 0 超级管理员
          userPwd: md5("123456"),
          state,
          deptId,
          roleList,
          job,
          mobile,
        })
        ctx.body = util.success('', '添加成功')
      } catch (error) {
        console.error('创建 user', error)
      }
    } else if (action === 'edit') {
      if (!deptId) {
        ctx.body = util.fail('部门不能为空', util.CODE.PARAM_ERROR);
        return;
      }
      try {
        await User.findByIdAndUpdate(_id, { mobile, userEmail, job, state, roleList, deptId })
        ctx.body = util.success('', '修改成功')
      } catch (error) {
        ctx.body = util.fail(`user 修改异常 ${res}`)
      }
    }
  } catch (error) {
    ctx.body = util.fail(`修改失败`)
    log4js.debug(error.stack)
  }
})

router.get('/all/list', async (ctx) => {
  console.log('user all list')
  try {
    // const list = await User.find({ state: 1 }, "_id userName userId userEmail");
    const list = await User.find({ state: 1 }, "");
    ctx.body = util.success(list);
  } catch (error) {
    ctx.body = util.fail(error.stack);
  }
})

// 获取用户对应权限的菜单
router.get('/getPermissionList', async ctx => {
  const authorization = ctx.request.headers.authorization;
  const {data} = util.decoded(authorization);
  const { role, roleList, state } = data;
  console.log('role:', role, 'roleList:', roleList);
  const menuList = await getMenuList(role, roleList);
  let actionList = getActionList(JSON.parse(JSON.stringify(menuList)))
  ctx.body = util.success({ menuList, actionList });
})

const getMenuList = async (userRole, roleKeys) => {
  let rootList = [];
  if (userRole === 0) {
    // 管理员, 查询所有的菜单
    rootList = await Menu.find({}) || [];
  } else {
    // 1. 找到角色
    // 2. 拿到角色下所有的菜单 id
    // 3. 将菜单 id 去重
    // 4. 将菜单组装成 three
    // 根据用的角色, 获取权限列表
    let permissionList = [];
    const roleList = await Role.find({ _id: {$in: roleKeys} });
    roleList.map(role => {
      const { checkedKeys, halfCheckedKeys } = role.permissionList;
      permissionList = permissionList.concat([...checkedKeys, ...halfCheckedKeys]);
    })
    permissionList = [...new Set(permissionList)];
    rootList = await Menu.find({ _id: { $in: permissionList } });
  }
  return util.getTreeMenu(rootList, null, []);
}

const getActionList = (list) => {
  const actionList = []
  const deep = arr => {
    while (arr.length) {
      const item = arr.pop();
      if (item.action) {
        item.action.map(action => {
          console.log('action:', action)
          if (action.menuCode) {
            actionList.push(action.menuCode)
          }
        })
      }
      if (item.children && !item.action) {
        deep(item.children);
      }
    }
  }
  deep(list);
  return actionList;
}

module.exports = router;
